package ph.com.gs3.chat.adapters;

import java.util.List;

import ph.com.gs3.chat.R;
import ph.com.gs3.chat.model.valueobject.business.Message;
import ph.com.gs3.chat.model.valueobject.business.UserStub;
import ph.com.gs3.chat.utilities.FLLogger;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ChatMessageListItemViewAdapter extends BaseAdapter {

	public static final String TAG = ChatMessageListItemViewAdapter.class.getSimpleName();

	public static final int MESSAGE_TYPE_OUTGOING = 0;
	public static final int MESSAGE_TYPE_INCOMING = 1;

	private Context context;
	private UserStub currentUser;
	private List<Message> messages;

	public ChatMessageListItemViewAdapter(Context context, UserStub currentUser,
	        List<Message> messages) {

		this.context = context;
		this.currentUser = currentUser;
		this.messages = messages;

	}

	@Override
	public int getCount() {
		return messages.size();
	}

	@Override
	public Object getItem(int position) {
		return messages.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public int getItemViewType(int position) {

		Message message = messages.get(position);

		return currentUser.getId().equals(message.getAuthor().getId()) ? MESSAGE_TYPE_OUTGOING
		        : MESSAGE_TYPE_INCOMING;
	}

	@Override
	public int getViewTypeCount() {
		return 2;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		MessageViewHolder holder;
		View rowView = convertView;

		Message data = (Message) getItem(position);

		if (rowView == null) {

			int layout;

			FLLogger.d(TAG, "current user: " + currentUser.getDisplayName());
			FLLogger.d(TAG, "from user: " + data.getAuthor().getDisplayName());

			if (getItemViewType(position) == MESSAGE_TYPE_OUTGOING) {
				layout = R.layout.view_outgoing_message;
			} else {
				layout = R.layout.view_incoming_message;
			}

			LayoutInflater inflater = (LayoutInflater) context
			        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			rowView = inflater.inflate(layout, parent, false);
			holder = new MessageViewHolder(rowView);
			rowView.setTag(holder);
		} else {
			holder = (MessageViewHolder) rowView.getTag();
		}

		holder.message.setText(data.getMessage());

		return rowView;
	}

	private class MessageViewHolder {

		TextView message;

		public MessageViewHolder(View rootView) {
			message = (TextView) rootView.findViewById(R.id.Chat_tvMessageText);
		}

	}

}
